﻿using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using UnityEngine;

public static class RectTransformExtensions
{
    public static void SetAnchor(this RectTransform source, AnchorPresets align, float offsetX = 0, float offsetY = 0)
    {
        switch (align)
        {
            case AnchorPresets.TopLeft:
                source.SetAnchorMinMax(0f, 1f, 0f, 1f);
                break;

            case AnchorPresets.TopCenter:
                source.SetAnchorMinMax(0.5f, 1f, 0.5f, 1f);
                break;

            case AnchorPresets.TopRight:
                source.SetAnchorMinMax(1f, 1f, 1f, 1f);
                break;

            case AnchorPresets.MiddleLeft:
                source.SetAnchorMinMax(0f, 0.5f, 0f, 0.5f);
                break;

            case AnchorPresets.MiddleCenter:
                source.SetAnchorMinMax(0.5f, 0.5f, 0.5f, 0.5f);
                break;

            case AnchorPresets.MiddleRight:
                source.SetAnchorMinMax(1f, 0.5f, 1f, 0.5f);
                break;

            case AnchorPresets.BottomLeft:
                source.SetAnchorMinMax(0f, 0f, 0f, 0f);
                break;

            case AnchorPresets.BottonCenter:
                source.SetAnchorMinMax(0.5f, 0f, 0.5f, 0f);
                break;

            case AnchorPresets.BottomRight:
                source.SetAnchorMinMax(1f, 0f, 1f, 0f);
                break;

            case AnchorPresets.StretchVerticalLeft:
                source.SetAnchorMinMax(0f, 0f, 0f, 1f);
                break;

            case AnchorPresets.StretchVerticalRight:
                source.SetAnchorMinMax(1f, 0f, 1f, 1f);
                break;

            case AnchorPresets.StretchVerticalCenter:
                source.SetAnchorMinMax(0.5f, 0f, 0.5f, 1f);
                break;

            case AnchorPresets.StretchHorizontalTop:
                source.SetAnchorMinMax(0f, 1f, 1f, 1f);
                break;

            case AnchorPresets.StretchHorizontalMiddle:
                source.SetAnchorMinMax(0f, 0.5f, 1f, 0.5f);
                break;

            case AnchorPresets.StretchHorizontalBottom:
                source.SetAnchorMinMax(0f, 0f, 1f, 0f);
                break;

            case AnchorPresets.StretchAll:
                source.SetAnchorMinMax(0f, 0f, 1f, 1f);
                break;
        }
        source.anchoredPosition = new Vector2(offsetX, offsetY);
    }

    private static void SetAnchorMinMax(this RectTransform source, float minX, float minY, float maxX, float maxY)
    {
        source.anchorMin = new Vector2(minX, minY);
        source.anchorMax = new Vector2(maxX, maxY);
        source.pivot = new Vector2((minX + maxX) / 2f, (minY + maxY) / 2f);
    }
}

